package ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.LayoutStyle.ComponentPlacement;

import model.City;
import model.Country;
import model.Outsider;
import util.EmailValidator;
import util.ImagePanel;
import util.Menu;
import util.PdfFilePrint;
import controller.CityController;
import controller.CountryController;
import controller.OutsiderController;
import controller.SupplierController;

public class SupplierUI implements ActionListener 
{
	private boolean startup = false;

	private static SupplierUI instance = null;

	private SupplierController supplierCtrl;
	private OutsiderController outsiderCtrl;
	private CountryController countryCtrl;
	private CityController cityCtrl;

	private EmailValidator emailValidator;

	private JFrame frameSupplierUI;

	private JTabbedPane tabbedPane;

	private JPanel redPanel;

	private Image image = null;

	private ImagePanel newSupplier;
	private ImagePanel allSuppliers;

	private JTable allSuppliersTable;
	private DefaultTableModel allSuppliersTableModel;

	private JComboBox<String> allSuppliersComboBoxSearchType;
	private JComboBox<String> newSupplierComboBoxStatus;
	private JComboBox<String> newSupplierComboBoxCountry;
	private JComboBox<String> newSupplierComboBoxCity;
	private JComboBox<String> editSupplierComboBoxCountry;
	private JComboBox<String> editSupplierComboBoxCity;

	private JButton newSupplierButtonCreateSupplier;
	private JButton allSuppliersButtonSearchClear;
	private JButton allSuppliersButtonEditSupplier;
	private JButton allSuppliersButtonDeactivateSupplier;
	private JButton statistics;

	private JCheckBox allSuppliersCheckBoxOnlyActiveSuppliers;

	private JTextField allSuppliersTextFieldSearchFor;
	private JTextField newSupplierTextFieldUsername;
	private JTextField newSupplierTextFieldPhoneNo;
	private JTextField newSupplierTextFieldEmail;

	private JMenuBar menu;

	private Menu menuBar;

	private ArrayList<JTextField> newSupplierTextFields;
	private ArrayList<JTextField> editSupplierTextFields;
	private JButton btnBack;

	private backButton back;
	private JButton btnPrint;

	public void display()
	{
		frameSupplierUI.getContentPane().add(redPanel);
		redPanel.add(tabbedPane);

		tabbedPane.add("All Suppliers", allSuppliers);
		tabbedPane.add("New Supplier", newSupplier);

		frameSupplierUI.setSize(800,420);
		frameSupplierUI.setLocationRelativeTo(null);
		frameSupplierUI.setVisible(true);
		frameSupplierUI.setResizable(false);
	}

	public SupplierUI()
	{
		frameSupplierUI = new JFrame("Supplier UI");

		back = new backButton();
		back.setNumber("5");

		menuBar = Menu.getInstance();

		menu = menuBar.makeJMenuBar();

		frameSupplierUI.setJMenuBar(menu);

		redPanel = new JPanel();
		redPanel.setBackground(new Color(165, 42, 42));

		tabbedPane = new JTabbedPane();

		cityCtrl = new CityController();
		countryCtrl = new CountryController();
		outsiderCtrl = new OutsiderController();
		supplierCtrl = new SupplierController();
		emailValidator = new EmailValidator();

		try
		{
			image = ImageIO.read(new File("img/background/background.jpg"));
		} 
		catch (IOException e)
		{
			msgError(null, "Could not load background image");
		}

		JLabel redPanelLabelTitle = new JLabel("SUPPLIER MENU");
		redPanelLabelTitle.setForeground(Color.WHITE);
		redPanelLabelTitle.setFont(new Font("Arial Unicode MS", Font.BOLD, 20));

		statistics = new JButton();
		statistics.setLocation(590, 327);
		statistics.setSize(100, 20);
		statistics.setOpaque(false);
		statistics.setText("Statistics");
		statistics.addActionListener(this);

		btnBack = new JButton();
		btnBack.addActionListener(this);
		btnBack.setText("Back");
		btnBack.setOpaque(false);
		btnBack.setBounds(9, 448, 100, 20);

		btnPrint = new JButton();
		btnPrint.addActionListener(this);
		btnPrint.setText("Print");
		btnPrint.setOpaque(false);

		GroupLayout gl_redTitle = new GroupLayout(redPanel);
		gl_redTitle.setHorizontalGroup(
				gl_redTitle.createParallelGroup(Alignment.TRAILING)
				.addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 794, Short.MAX_VALUE)
				.addGroup(gl_redTitle.createSequentialGroup()
						.addContainerGap()
						.addComponent(redPanelLabelTitle)
						.addContainerGap(611, Short.MAX_VALUE))
						.addGroup(Alignment.LEADING, gl_redTitle.createSequentialGroup()
								.addContainerGap()
								.addComponent(btnBack)
								.addPreferredGap(ComponentPlacement.RELATED, 509, Short.MAX_VALUE)
								.addComponent(btnPrint, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(statistics, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
								.addContainerGap())
				);
		gl_redTitle.setVerticalGroup(
				gl_redTitle.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_redTitle.createSequentialGroup()
						.addComponent(redPanelLabelTitle)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 309, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addGroup(gl_redTitle.createParallelGroup(Alignment.BASELINE)
								.addComponent(btnBack)
								.addComponent(statistics, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
								.addComponent(btnPrint, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE))
								.addContainerGap())
				);

		redPanel.setLayout(gl_redTitle);

		/******************************************************
		 * 
		 * New Supplier pane
		 * 
		 ******************************************************/

		newSupplier = new ImagePanel(image);

		JLabel newSupplierLabelName = new JLabel("Supplier Name:");
		JLabel newSupplierLabelPhoneno = new JLabel("Supplier PhoneNo:");
		JLabel newSupplierLabelEmail = new JLabel("Supplier E-mail:");
		JLabel newSupplierLabelStatus = new JLabel("Supplier Status:");
		JLabel newSupplierLabelCountry = new JLabel("Supplier Country:");
		JLabel newSupplierLabelCity = new JLabel("Supplier City:");

		newSupplierTextFieldUsername = new JTextField();
		newSupplierTextFieldUsername.setColumns(10);

		newSupplierTextFieldPhoneNo = new JTextField();
		newSupplierTextFieldPhoneNo.setColumns(10);

		newSupplierTextFieldEmail = new JTextField();
		newSupplierTextFieldEmail.setColumns(10);

		newSupplierComboBoxStatus = new JComboBox<String>();
		newSupplierComboBoxStatus.setOpaque(false);
		newSupplierComboBoxStatus.addItem("Active");
		newSupplierComboBoxStatus.addItem("Inactive");

		newSupplierComboBoxCountry = new JComboBox<String>();
		newSupplierComboBoxCountry.setOpaque(false);
		newSupplierComboBoxCountry.addActionListener(this);

		newSupplierComboBoxCity = new JComboBox<String>();
		newSupplierComboBoxCity.setOpaque(false);
		newSupplierComboBoxCity.setEnabled(false);

		newSupplierButtonCreateSupplier = new JButton("Create Supplier");
		newSupplierButtonCreateSupplier.setOpaque(false);
		newSupplierButtonCreateSupplier.addActionListener(this);
		newSupplierButtonCreateSupplier.setEnabled(false);

		newSupplierTextFields = new ArrayList<JTextField>();
		newSupplierTextFields.add(newSupplierTextFieldUsername);
		newSupplierTextFields.add(newSupplierTextFieldPhoneNo);
		newSupplierTextFields.add(newSupplierTextFieldEmail);

		GroupLayout gl_newSupplier = new GroupLayout(newSupplier);
		gl_newSupplier.setHorizontalGroup(
				gl_newSupplier.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_newSupplier.createSequentialGroup()
						.addGap(277)
						.addGroup(gl_newSupplier.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_newSupplier.createSequentialGroup()
										.addComponent(newSupplierLabelCountry)
										.addGap(44)
										.addComponent(newSupplierComboBoxCountry, 0, 107, Short.MAX_VALUE))
										.addGroup(gl_newSupplier.createSequentialGroup()
												.addGroup(gl_newSupplier.createParallelGroup(Alignment.LEADING)
														.addComponent(newSupplierLabelName)
														.addComponent(newSupplierLabelPhoneno)
														.addComponent(newSupplierLabelEmail)
														.addComponent(newSupplierLabelStatus))
														.addGap(40)
														.addGroup(gl_newSupplier.createParallelGroup(Alignment.LEADING)
																.addComponent(newSupplierComboBoxStatus, 0, 107, Short.MAX_VALUE)
																.addComponent(newSupplierTextFieldPhoneNo, 107, 107, 107)
																.addComponent(newSupplierTextFieldUsername, 107, 107, 107)
																.addComponent(newSupplierTextFieldEmail, GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)))
																.addGroup(gl_newSupplier.createSequentialGroup()
																		.addComponent(newSupplierLabelCity)
																		.addGap(64)
																		.addGroup(gl_newSupplier.createParallelGroup(Alignment.LEADING)
																				.addComponent(newSupplierButtonCreateSupplier, GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
																				.addComponent(newSupplierComboBoxCity, 0, 107, Short.MAX_VALUE))))
																				.addGap(277))
				);
		gl_newSupplier.setVerticalGroup(
				gl_newSupplier.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_newSupplier.createSequentialGroup()
						.addGap(36)
						.addGroup(gl_newSupplier.createParallelGroup(Alignment.BASELINE)
								.addComponent(newSupplierTextFieldUsername, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(newSupplierLabelName))
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addGroup(gl_newSupplier.createParallelGroup(Alignment.BASELINE)
										.addComponent(newSupplierLabelPhoneno)
										.addComponent(newSupplierTextFieldPhoneNo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(ComponentPlacement.UNRELATED)
										.addGroup(gl_newSupplier.createParallelGroup(Alignment.BASELINE)
												.addComponent(newSupplierTextFieldEmail, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addComponent(newSupplierLabelEmail))
												.addPreferredGap(ComponentPlacement.UNRELATED)
												.addGroup(gl_newSupplier.createParallelGroup(Alignment.BASELINE)
														.addComponent(newSupplierLabelStatus)
														.addComponent(newSupplierComboBoxStatus, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
														.addPreferredGap(ComponentPlacement.UNRELATED)
														.addGroup(gl_newSupplier.createParallelGroup(Alignment.BASELINE)
																.addComponent(newSupplierLabelCountry)
																.addComponent(newSupplierComboBoxCountry, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																.addPreferredGap(ComponentPlacement.UNRELATED)
																.addGroup(gl_newSupplier.createParallelGroup(Alignment.BASELINE)
																		.addComponent(newSupplierLabelCity)
																		.addComponent(newSupplierComboBoxCity, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE))
																		.addPreferredGap(ComponentPlacement.UNRELATED)
																		.addComponent(newSupplierButtonCreateSupplier)
																		.addContainerGap(36, Short.MAX_VALUE))
				);
		newSupplier.setLayout(gl_newSupplier);

		/******************************************************
		 * 
		 * All Suppliers pane
		 * 
		 ******************************************************/

		allSuppliers = new ImagePanel(image);

		String allSuppliersColumns [] = { "#", "Username", "PhoneNo", "Email", "City", "Country", "", "Active" };
		allSuppliersTableModel = new DefaultTableModel(null, allSuppliersColumns);

		allSuppliersTable = new JTable(allSuppliersTableModel)
		{
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex) 
			{
				return false;
			}

			public Class<?> getColumnClass(int column)   
			{   
				return getValueAt(0, column).getClass();   
			}  
		};

		Dimension dim = allSuppliersTable.getPreferredSize(); 
		double width = dim.width / allSuppliersColumns.length; 
		double[] width_2 = { 0.3, 1.2, 1.2, 2, 1, 1, 1, 0.5, 0.5 };

		for (int i = 0; i < allSuppliersColumns.length; i++)
			allSuppliersTable.getColumnModel().getColumn(i).setPreferredWidth((int) (width*width_2[i])); 

		allSuppliersTable.setAutoCreateRowSorter(true);

		allSuppliersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane allSuppliersTableScroll = new JScrollPane(allSuppliersTable);

		JLabel allSuppliersLabelSearchBy = new JLabel("Search by:");
		JLabel allSuppliersLabelSearchFor = new JLabel("Search for:");

		allSuppliersComboBoxSearchType = new JComboBox<String>();
		allSuppliersComboBoxSearchType.setOpaque(false);
		allSuppliersComboBoxSearchType.addActionListener(this);
		allSuppliersComboBoxSearchType.addItem("Everything");
		allSuppliersComboBoxSearchType.addItem("Name");
		allSuppliersComboBoxSearchType.addItem("Email");
		allSuppliersComboBoxSearchType.addItem("PhoneNo");
		allSuppliersComboBoxSearchType.addItem("City");
		allSuppliersComboBoxSearchType.addItem("Country");

		allSuppliersTextFieldSearchFor = new JTextField();
		allSuppliersTextFieldSearchFor.getDocument().addDocumentListener(new DocumentListener()
		{
			@Override
			public void insertUpdate(DocumentEvent e)
			{
				// most likely to never be used .. 
				searchSuppliers();						
			}

			@Override
			public void changedUpdate(DocumentEvent e)
			{
				searchSuppliers();
			}

			@Override
			public void removeUpdate(DocumentEvent e)
			{
				searchSuppliers();
			}
		});

		allSuppliersButtonSearchClear = new JButton("Clear search");
		allSuppliersButtonSearchClear.setOpaque(false);
		allSuppliersButtonSearchClear.addActionListener(this);

		allSuppliersButtonEditSupplier = new JButton("Edit Supplier");
		allSuppliersButtonEditSupplier.setOpaque(false);
		allSuppliersButtonEditSupplier.addActionListener(this);

		allSuppliersButtonDeactivateSupplier = new JButton("Deactivate Supplier");
		allSuppliersButtonDeactivateSupplier.setOpaque(false);
		allSuppliersButtonDeactivateSupplier.addActionListener(this);

		allSuppliersCheckBoxOnlyActiveSuppliers = new JCheckBox("Only active Suppliers");
		allSuppliersCheckBoxOnlyActiveSuppliers.setOpaque(false);
		allSuppliersCheckBoxOnlyActiveSuppliers.setSelected(true);
		allSuppliersCheckBoxOnlyActiveSuppliers.addActionListener(this);

		GroupLayout gl_allSuppliers = new GroupLayout(allSuppliers);
		gl_allSuppliers.setHorizontalGroup(
				gl_allSuppliers.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_allSuppliers.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_allSuppliers.createParallelGroup(Alignment.LEADING)
								.addComponent(allSuppliersTableScroll, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 769, Short.MAX_VALUE)
								.addGroup(gl_allSuppliers.createSequentialGroup()
										.addGroup(gl_allSuppliers.createParallelGroup(Alignment.LEADING)
												.addComponent(allSuppliersLabelSearchBy)
												.addComponent(allSuppliersLabelSearchFor))
												.addGap(24)
												.addGroup(gl_allSuppliers.createParallelGroup(Alignment.LEADING, false)
														.addComponent(allSuppliersComboBoxSearchType, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(allSuppliersTextFieldSearchFor, GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE))
														.addGap(18)
														.addGroup(gl_allSuppliers.createParallelGroup(Alignment.LEADING)
																.addGroup(gl_allSuppliers.createSequentialGroup()
																		.addComponent(allSuppliersButtonSearchClear)
																		.addPreferredGap(ComponentPlacement.RELATED, 197, Short.MAX_VALUE)
																		.addComponent(allSuppliersButtonEditSupplier)
																		.addPreferredGap(ComponentPlacement.UNRELATED)
																		.addComponent(allSuppliersButtonDeactivateSupplier))
																		.addComponent(allSuppliersCheckBoxOnlyActiveSuppliers))))
																		.addContainerGap())
				);
		gl_allSuppliers.setVerticalGroup(
				gl_allSuppliers.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_allSuppliers.createSequentialGroup()
						.addContainerGap(30, Short.MAX_VALUE)
						.addGroup(gl_allSuppliers.createParallelGroup(Alignment.BASELINE)
								.addComponent(allSuppliersLabelSearchBy)
								.addComponent(allSuppliersComboBoxSearchType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(allSuppliersCheckBoxOnlyActiveSuppliers))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(gl_allSuppliers.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_allSuppliers.createParallelGroup(Alignment.BASELINE)
												.addComponent(allSuppliersLabelSearchFor)
												.addComponent(allSuppliersButtonDeactivateSupplier)
												.addComponent(allSuppliersButtonEditSupplier))
												.addGroup(gl_allSuppliers.createParallelGroup(Alignment.BASELINE)
														.addComponent(allSuppliersTextFieldSearchFor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
														.addComponent(allSuppliersButtonSearchClear)))
														.addPreferredGap(ComponentPlacement.RELATED)
														.addComponent(allSuppliersTableScroll, GroupLayout.PREFERRED_SIZE, 179, GroupLayout.PREFERRED_SIZE)
														.addGap(63))
				);
		allSuppliers.setLayout(gl_allSuppliers);

		try
		{
			searchSuppliers();
			updateCountries(newSupplierComboBoxCountry, true);
		}
		catch (Exception e)
		{
			msgError(allSuppliers, "Could not load properly");
		}
	}

	/**
	 * ActionPerformed.. where all the magic happens.
	 * Our listener for every action which happens.
	 * 
	 * @param 	e		the event which has triggered the listener
	 * 
	 * @return 	void 
	 */
	@Override
	public void actionPerformed(ActionEvent e)
	{
		frameSupplierUI.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

		if (e.getSource() == allSuppliersCheckBoxOnlyActiveSuppliers)
		{
			searchSuppliers();
		}
		else if(e.getSource() == statistics)
		{
			StatisticsUI stats = StatisticsUI.getInstance();
			stats.display();
			frameSupplierUI.setVisible(false);
		}
		else if (e.getSource() == allSuppliersButtonSearchClear)
		{
			allSuppliersComboBoxSearchType.setSelectedIndex(0);
			allSuppliersTextFieldSearchFor.setText(null);
		}
		else if (e.getSource() == allSuppliersComboBoxSearchType)
		{
			if (startup)
			{
				allSuppliersTextFieldSearchFor.setText(null);

				searchSuppliers();
			}
		}
		else if (e.getSource() == allSuppliersButtonEditSupplier)
		{
			showEditSupplierDialog();
		}
		else if (e.getSource() == newSupplierComboBoxCountry) 
		{
			updateCities((newSupplierComboBoxCountry.getSelectedIndex() > 0), newSupplierComboBoxCity, newSupplierComboBoxCountry);
		}
		else if (e.getSource() == editSupplierComboBoxCountry)
		{
			updateCities(true, editSupplierComboBoxCity, editSupplierComboBoxCountry);
		}
		else if (e.getSource() == newSupplierButtonCreateSupplier)
		{
			addSupplier();
		}
		else if (e.getSource() == allSuppliersButtonDeactivateSupplier)
		{
			activateSupplier();
		}
		else if(e.getSource() == btnBack)
		{
			back.goBack(back.getNumber());
		}
		else if(e.getSource() == btnPrint)
		{
			printSupplierPDF();
		}
		
		frameSupplierUI.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	}

	private void printSupplierPDF()
	{
		if (allSuppliersTable.getRowCount() > 0)
		{
			ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

			String columns [] = { "#", "Username", "PhoneNo", "Email", "City", "Country", "Active" };

			ArrayList<String> supplierID = new ArrayList<String>();
			ArrayList<String> supplierUsername = new ArrayList<String>();
			ArrayList<String> supplierPhoneNo = new ArrayList<String>();
			ArrayList<String> supplierEmail = new ArrayList<String>();
			ArrayList<String> supplierCity = new ArrayList<String>();
			ArrayList<String> supplierCountry = new ArrayList<String>();
			ArrayList<String> supplierActive = new ArrayList<String>();

			list.add(supplierID);
			list.add(supplierUsername);
			list.add(supplierPhoneNo);
			list.add(supplierEmail);
			list.add(supplierCity);
			list.add(supplierCountry);
			list.add(supplierActive);

			for(int i = 0; i < allSuppliersTable.getRowCount(); i++)
			{
				list.get(0).add(String.valueOf(allSuppliersTable.getValueAt(i, 0)));
				list.get(1).add(String.valueOf(allSuppliersTable.getValueAt(i, 1)));
				list.get(2).add(String.valueOf(allSuppliersTable.getValueAt(i, 2)));
				list.get(3).add(String.valueOf(allSuppliersTable.getValueAt(i, 3)));
				list.get(4).add(String.valueOf(allSuppliersTable.getValueAt(i, 4)));
				list.get(5).add(String.valueOf(allSuppliersTable.getValueAt(i, 5)));
				list.get(6).add(String.valueOf(allSuppliersTable.getValueAt(i, 7)).contains("yes") ? "Yes" : "No");
			}

			PdfFilePrint pdfPrint = new PdfFilePrint();
			boolean successPDF = pdfPrint.PDFPrint("Supplier", "Current Suppliers", "supplier", "Nikola", columns, list);

			if(successPDF)
				msgSuccess(null, "PDF was created successfully");
			else
				msgError(null, "There was an error creating the PDF");
		}
		else
		{
			msgError(null, "Nothing to print");
		}
	}

	/**
	 * Necessary checks when adding a Supplier
	 * 
	 * @return	void
	 */
	private void addSupplier()
	{
		boolean validInfo = SupplierCheckValidInfo(newSupplierTextFields);
		boolean validEmail = emailValidator.validate(newSupplierTextFieldEmail.getText());

		if (validInfo && validEmail)
		{
			try
			{
				int success = outsiderCtrl.createOutsider(newSupplierTextFieldUsername.getText(),  newSupplierTextFieldPhoneNo.getText(), cityCtrl.getOneCity("name", newSupplierComboBoxCity.getSelectedItem().toString(), newSupplierComboBoxCountry.getSelectedItem().toString()), (newSupplierComboBoxStatus.getSelectedIndex() == 0), newSupplierTextFieldEmail.getText(), 0);

				if (success > 0)
				{
					msgSuccess(newSupplier, "Supplier \"" + newSupplierTextFieldUsername.getText() + "\" has been added successfully");

					for(JTextField tf : newSupplierTextFields)
						tf.setText(null);

					searchSuppliers();
					updateCountries(newSupplierComboBoxCountry, true);
				}
				else
				{
					msgError(newSupplier, "There was an error adding the Supplier.\nThis username already exists in the system.");					
				}
			}
			catch (Exception ex)
			{
				msgError(newSupplier, "There was an error adding the Supplier.\nThis username already exists in the system.");
			}
		}
		else 
		{
			String error = "You cannot proceed due some errors:\n\n";

			if (!validInfo)
				error += " - You haven't filled up every text area or a field exceeds 32 symbols\n";

			if (!validEmail)
				error += " - Email is not valid\n";

			msgError(newSupplier, error);
		}		
	}

	/**
	 * Necessary checks (and dialog opening) when editing a supplier
	 * 
	 * @return	void
	 */
	private void showEditSupplierDialog()
	{
		if (allSuppliersTable.getSelectedRow() > -1) 
		{
			try
			{
				int SupplierID = Integer.valueOf(String.valueOf(allSuppliersTable.getValueAt(allSuppliersTable.getSelectedRow(), 0)));

				Outsider editSupplier = supplierCtrl.searchSupplierID(SupplierID);

				JPanel panel = new JPanel(new GridLayout(0, 2, 5, 5));

				JTextField editSupplierTextFieldSupplierName = new JTextField(editSupplier.getName());
				JTextField editSupplierTextFieldSupplierPhoneNo = new JTextField(editSupplier.getPhoneNo());
				JTextField editSupplierTextFieldSupplierEmail = new JTextField(editSupplier.getEmail());

				JComboBox<String> editSupplierComboBoxActive = new JComboBox<String>();
				editSupplierComboBoxActive.addItem("Active");
				editSupplierComboBoxActive.addItem("Inactive");
				editSupplierComboBoxActive.setSelectedIndex(editSupplier.isActive() ? 0 : 1);

				editSupplierComboBoxCountry = new JComboBox<String>();
				updateCountries(editSupplierComboBoxCountry, false);
				editSupplierComboBoxCountry.setSelectedItem(editSupplier.getCity().getCountry().getName());
				editSupplierComboBoxCountry.addActionListener(this);

				editSupplierComboBoxCity = new JComboBox<String>();
				updateCities(true, editSupplierComboBoxCity, editSupplierComboBoxCountry);
				editSupplierComboBoxCity.setSelectedItem(editSupplier.getCity().getName());

				panel.add(new JLabel("Supplier Name:"));
				panel.add(editSupplierTextFieldSupplierName);
				panel.add(new JLabel("Supplier PhoneNo:"));
				panel.add(editSupplierTextFieldSupplierPhoneNo);
				panel.add(new JLabel("Supplier E-mail:"));
				panel.add(editSupplierTextFieldSupplierEmail);
				panel.add(new JLabel("Supplier Status:"));
				panel.add(editSupplierComboBoxActive);
				panel.add(new JLabel("Supplier Country:"));
				panel.add(editSupplierComboBoxCountry);
				panel.add(new JLabel("Supplier City:"));
				panel.add(editSupplierComboBoxCity);

				editSupplierTextFields = new ArrayList<JTextField>();
				editSupplierTextFields.add(editSupplierTextFieldSupplierName);
				editSupplierTextFields.add(editSupplierTextFieldSupplierPhoneNo);
				editSupplierTextFields.add(editSupplierTextFieldSupplierEmail);

				int option = JOptionPane.showConfirmDialog(allSuppliers, panel, "Edit Supplier", JOptionPane.OK_CANCEL_OPTION);

				if (option == JOptionPane.YES_OPTION)
				{
					boolean validInfo = SupplierCheckValidInfo(editSupplierTextFields);
					boolean validEmail = emailValidator.validate(editSupplierTextFieldSupplierEmail.getText());

					if (validInfo && validEmail)
					{
						int success = outsiderCtrl.updateOutsider(SupplierID, editSupplierTextFieldSupplierName.getText(), editSupplierTextFieldSupplierPhoneNo.getText(),  cityCtrl.getOneCity("name",editSupplierComboBoxCity.getSelectedItem().toString(), editSupplierComboBoxCountry.getSelectedItem().toString()), (editSupplierComboBoxActive.getSelectedIndex() == 0), editSupplierTextFieldSupplierEmail.getText(), 0);

						if (success > 0)
						{
							msgSuccess(newSupplier, "Supplier #" + SupplierID + " has been edited successfully");

							searchSuppliers();
						}
						else 
						{
							msgError(newSupplier, "There is already a supplier with that name or email");
						}
					}
					else 
					{
						String error = "You cannot proceed due some errors:\n\n";

						if (!validInfo)
							error += " - You haven't filled up every text area\n";

						if (!validEmail)
							error += " - Email is not valid\n";

						msgError(newSupplier, error);
					}
				}
			}
			catch (SQLException ex)
			{
				msgError(allSuppliers, "There was a problem loading the Supplier");
			}
		}
		else 
		{
			msgError(allSuppliers, "You have not selected a Supplier");
		}
	}

	/**
	 * Returns if the two ArrayLists which are given are not empty
	 *
	 * @param  	textFields  	an array list with all the text fields which need to be checked
	 * 
	 * @return	true			if they are not empty
	 * 
	 */
	private boolean SupplierCheckValidInfo(ArrayList<JTextField> textFields)
	{
		for(JTextField tf : textFields)
		{
			if ((tf.getText().trim().length() == 0) || (tf.getText().trim().length() > 32))
				return false;
		}

		return true;
	}

	/**
	 * Updates a certain JComboBox by adding all the cities from a certain
	 * selected country on another JComboBox
	 *
	 * @param  	notEmpty			should the city combo box be empty or not
	 * @param  	cityComboBox		the combo box which will be updated after calling this method
	 * @param	countryComboBox		the combo box from which we get the selected city in order to show only cities from this country
	 * 
	 * @return	void
	 */
	private void updateCities(boolean notEmpty, JComboBox<String> cityComboBox, JComboBox<String> countryComboBox)
	{
		cityComboBox.removeAllItems();
		cityComboBox.setEnabled(notEmpty);

		newSupplierButtonCreateSupplier.setEnabled(notEmpty);

		if (notEmpty)
		{
			ArrayList<City> cityList = null;

			try
			{
				cityList = cityCtrl.getCitiesByCountryName(countryComboBox.getSelectedItem().toString());

				for(City city : cityList)
				{
					cityComboBox.addItem(city.getName());
				}
			}
			catch(Exception e)
			{
				msgError(newSupplier, "Could not load cities or this country has no cities set");
			}
		}
	}

	/**
	 * Updates a certain JComboBox by adding all the countries
	 *
	 * @param  	comboBox 		the combo box which will be updated after calling this method
	 * @param	emptyField		should the combo box have one empty field on top
	 * 
	 * @return	void
	 */
	private void updateCountries(JComboBox<String> comboBox, boolean emptyField)
	{
		comboBox.removeAllItems();

		if (emptyField)
			comboBox.addItem(null);

		ArrayList<Country> countryList = null;

		try
		{
			countryList = countryCtrl.getAllCountries();

			for(Country country : countryList)
				comboBox.addItem(country.getName());
		}
		catch(Exception e)
		{
			msgError(newSupplier, "Could not load countries");
		}
	}

	/**
	 * Updating the all Supplier table
	 *
	 * @param  	SupplierList 	the array list which is put in the table
	 * 
	 * @return	void
	 */
	private void allSuppliersUpdateTable(ArrayList<Outsider> supplierList)
	{
		if (supplierList.size() > 0)
		{
			tableClearList();

			for(Outsider supplier : supplierList)
			{
				allSuppliersTableModel.addRow(
						new Object[]
								{ 
								supplier.getOutsiderID(), 
								supplier.getName(),
								supplier.getPhoneNo(),
								supplier.getEmail(),
								supplier.getCity().getName(),
								supplier.getCity().getCountry().getName(),
								new ImageIcon("img/flags/" + supplier.getCity().getCountry().getTld() + ".png"),
								new ImageIcon("img/tick_" + (supplier.isActive() ? "yes" : "no") + ".png")
								} 
						);
			}
		}
	}

	/**
	 * Removing all rows from the all Supplier table
	 *
	 * @return	void
	 */
	private void tableClearList()
	{
		DefaultTableModel dm = (DefaultTableModel) allSuppliersTable.getModel();

		while(dm.getRowCount() > 0)
			dm.removeRow(0);
	}

	/**
	 * Activating/deactivating a Supplier
	 *
	 * @return	void
	 */
	public void activateSupplier()
	{
		DefaultTableModel model = (DefaultTableModel) allSuppliersTable.getModel();
		int[] rows = allSuppliersTable.getSelectedRows();

		for (int i = 0; i < rows.length; i++)
		{
			int SupplierID = Integer.valueOf((String.valueOf(model.getValueAt(rows[i]-i,0))));

			try
			{
				if (outsiderCtrl.activateOutsider(SupplierID) > 0)
				{
					msgSuccess(allSuppliers, "Successfully changed " + String.valueOf(model.getValueAt(rows[i]-i,1)) + "'s status");

					searchSuppliers();
				}
			}
			catch (SQLException e)
			{
				msgError(allSuppliers, "There was an error changing " + String.valueOf(model.getValueAt(rows[i]-i,1)) + "'s status");
			}
		}
	}

	/**
	 * Searching Supplier based on the selected drop down criteria 
	 * and input text field
	 * 
	 * @return	void
	 */
	private void searchSuppliers()
	{
		ArrayList<Outsider> SupplierList = new ArrayList<Outsider>();

		boolean active = allSuppliersCheckBoxOnlyActiveSuppliers.isSelected();

		String clause = allSuppliersComboBoxSearchType.getSelectedItem().toString().toLowerCase();
		String search = allSuppliersTextFieldSearchFor.getText();

		try
		{
			switch (clause)
			{
				case "everything": 	SupplierList = supplierCtrl.searchSupplierEverything(active, search); break;
				case "name":		SupplierList = supplierCtrl.searchSupplierName(active, search); break;
				case "email":		SupplierList = supplierCtrl.searchSupplierEmail(active, search); break;
				case "phoneno":		SupplierList = supplierCtrl.searchSupplierPhoneNo(active, search); break;
				case "city":		SupplierList = supplierCtrl.searchSupplierCity(active, search); break;
				case "country":		SupplierList = supplierCtrl.searchSupplierCountry(active, search); break;
			}

			if (SupplierList.size() > 0)
				allSuppliersUpdateTable(SupplierList);
			else
				tableClearList();
		}
		catch (Exception e)
		{
			msgError(allSuppliers, "Could not load Suppliers");
			e.printStackTrace();
		}

		if (!startup)
			startup = true;
	}

	/**
	 * Shows an error message pop-up
	 * 
	 * @param	panel 		on which panel should it show the message
	 * @param	error		the error which is printed on the pop-up window
	 * 
	 * @return	void
	 */
	private void msgError(JPanel panel, String error)
	{
		JOptionPane.showConfirmDialog(panel, error, "Error", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * Shows a success message pop-up
	 * 
	 * @param	panel 		on which panel should it show the message
	 * @param	success		the success message which is printed on the pop-up window
	 * 
	 * @return	void
	 */
	private void msgSuccess(JPanel panel, String success)
	{
		JOptionPane.showMessageDialog(panel, success, "Success", 1);
	}

	public static SupplierUI getInstance()
	{
		if(instance == null)
			instance = new SupplierUI();

		return instance;			
	}

	public static void main(String[] args)
	{
		try 
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 

			SupplierUI SupplierMenu = new SupplierUI();
			SupplierMenu.display();
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Supplier Menu could not load");
			e.printStackTrace();
		}
	}
}